const router = require('koa-router')()
const { exec } = require('../db/index')
const jwt = require('jsonwebtoken');

router.prefix('/api');

// 中间件 函数
const auth = async (ctx, next) => {
  let { authorization } = ctx.request.header;
  console.log(authorization, 'authorization')
  // if (authorization) {
  //   await next()
  // }
}

// 开房案例： 房卡
router.post('/login', async (ctx, next) => {
  let { username, password } = ctx.request.body;
  let data = await exec(`select * from users where username='${username}' and password='${password}' `)
  let token = jwt.sign({ ...data[0] }, 'key', { expiresIn: '1h' })
  ctx.body = {
    code: 0,
    msg: 'success',
    token
  }
})

// 添加
router.post('/user', auth, async (ctx, next) => {
  const { skuid, username, gender, address } = ctx.request.body;
  const list = await exec(`select * from week2 where skuid=${skuid}`)
  if (!list.length) {
    const data = await exec(`insert into week2 (skuid, username, gender, address) values ('${skuid}','${username}',${gender},'${address}')`)
    ctx.body = { code: 0, msg: 'success', id: data.affectedRows };
  } else {
    ctx.body = { code: -1, msg: '学号已经存在了' }
  }
})
// 删除多条数据
router.delete('/user/:ids', auth, async (ctx, next) => {
  /// 1-2-3   1,2,3
  let str = ctx.params.ids.split('-').join(',')
  // console.log('sql: => ', `delete from week2 where id in (${str})`)
  let data = await exec(`delete from week2 where id in (${str})`)
  ctx.body = {
    data
  }
})
// 查询分页
router.get('/user', async (ctx, next) => {
  const { page, size } = ctx.query;
  let data;
  if (page && size) {
    data = await exec(`select * from week2 limit ${size} offset ${page * size}`);
  } else {
    data = await exec(`select * from week2`)
  }
  ctx.body = { code: 0, data }
})
// 更新数据
router.put('/user/:id', auth, async (ctx, next) => {
  const { id } = ctx.params;
  const { skuid, username, gender, address, } = ctx.request.body;
  const list = await exec(`select * from week2 where skuid=${skuid}`)
  if (!list.length) {
    // moment;
    const data = await exec(`update week2 set skuid='${skuid}', username='${username}', 
    gender=${gender}, address='${address}' updateTime=${'2020-05-28'} where id = ${id}`)
    ctx.body = { code: 0, msg: 'success', data }
  } else {
    ctx.body = { code: -1, msg: 'fail' }
  }
})

module.exports = router
